package com.yhy.common.wechat.util;

import cn.hutool.json.JSONUtil;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayAppOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.yhy.common.wechat.config.WxConfig;
import com.yhy.common.wechat.model.WxResult;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.util.Objects;

@Slf4j
public class WxPayUtil {

    /**
     * 微信支付参数
     *
     * @param appId      appid
     * @param openId     openid
     * @param orderNo    订单唯一编号
     * @param amount     金额/单位: 分
     * @param info       商品描述信息
     * @param detailJSON 订单详情，回调时会返回
     * @param timeStart  开始时间
     * @param timeExpire 过期时间
     * @return WxResult<WxPayAppOrderResult>
     */
    @SneakyThrows
    public static WxResult<WxPayAppOrderResult> createUnifiedOrder(String appId, String openId, String orderNo
            , Integer amount, String info, String detailJSON, String timeStart, String timeExpire) {
        final WxPayService service = WxConfig.getPayServices().get(appId);
        if (Objects.isNull(service) || !service.switchover(appId)) {
            throw new IllegalArgumentException(String.format("未找到对应appId=[%s]的配置，请核实！", appId));
        }
        WxPayUnifiedOrderRequest unifiedOrderRequest = new WxPayUnifiedOrderRequest();
        unifiedOrderRequest
                .setOpenid(openId)
                .setOutTradeNo(orderNo)
                .setBody(info)
                .setDetail(detailJSON)
                .setTotalFee(amount)
                .setTimeStart(timeStart)
                .setTimeExpire(timeExpire)
                .setSpbillCreateIp(InetAddress.getLoopbackAddress().getHostAddress())
                .setSignType("MD5");
        WxPayAppOrderResult result = service.createOrder(unifiedOrderRequest);
        log.debug("【统一下单 生成预支付交易单】成功，构建前端响应参数:" + JSONUtil.toJsonStr(result));
        return WxResult.ok(result);
    }

    public static WxResult<WxPayOrderNotifyResult> parseOrderNotifyResult(String appId, String xmlResult) {
        WxPayService wxPayService = WxConfig.getPayServices().get(appId);
        WxPayOrderNotifyResult wxPayOrderNotifyResult;
        try {
            wxPayOrderNotifyResult = wxPayService.parseOrderNotifyResult(xmlResult);
        } catch (WxPayException e) {
            log.error("解析支付回调信息失败: {}", e.getLocalizedMessage(), e);
            return WxResult.fail(e);
        }
        return WxResult.ok(wxPayOrderNotifyResult);
    }
}
